<script setup lang="ts">
	import { useMessageConfirm } from '@/hooks/messageConfirm/useMessageConfirm.ts';
	import { useDebounceFn, useInfiniteScroll, useResizeObserver, useThrottleFn } from '@vueuse/core';
	import type { NoteBookEntity, NoteOftenEntity } from '@/entity/note/NoteEntity';
	import { useBarAction } from '@/hooks/useBarComps';
	import { ApiNoteOftenAdd, ApiNoteOftenList, ApiNoteOftenRemove } from '@/api/note/often';
	import { Message } from '@arco-design/web-vue';
	import { ApiNoteBookDelete, ApiNoteBookPage, ApiNoteBookUpdate } from '@/api/note/noteBook';
	import { FILE_PREVIEW } from '@/enums/appEnum';
	import NoteBookAdd from '@/views/note/components/NoteBookAdd.vue';
	import { useCompRef, useUploadFile } from '@/hooks/useComp';
	import { ApiUpload } from '@/api/common';
	import { fileToFormData } from '@/utils/utils';
	import DropdownAction from '@/components/DropdownAction/DropdownAction';

	/**
	 * 笔记类型
	 */
	const noteType = inject('noteType');

	const router = useRouter();
	const everydayRef = ref();

	const query = ref({
		pageNo: 1,
		pageSize: 28,
		type: noteType,
	});

	let pageNoTotal = 0;

	/**
	 * 常用本
	 */
	const noteOftenList = ref<NoteOftenEntity[]>([]);

	/**
	 * 笔记本列表
	 */
	const noteBookList = ref<NoteBookEntity[]>([]);

	/**
	 * 获取常用本
	 */
	async function getOftenList() {
		noteOftenList.value = await ApiNoteOftenList({});
	}

	/**
	 * 获取笔记本列表
	 */
	async function getNoteBookList() {
		const data = await ApiNoteBookPage(query.value);
		noteBookList.value = data.list;

		if (pageNoTotal === 0) {
			pageNoTotal = Math.ceil(data.total / query.value.pageSize);
		}
	}

	function getData() {
		getNoteBookList();
		getOftenList();
	}

	getData();

	/**
	 * 删除笔记本
	 */
	async function deleteNote(v: NoteBookEntity) {
		await ApiNoteBookDelete(v.id);
		query.value.pageNo = 1;
		getData();
		Message.success('操作成功');
	}

	/**
	 * 添加常用
	 */
	async function addOften(id?: string | number) {
		await ApiNoteOftenAdd(id);
		Message.success('操作成功');
		getData();
	}

	/**
	 * 移出常用
	 */
	async function removeOften(id?: string | number) {
		await ApiNoteOftenRemove(id);
		getData();
		Message.success('操作成功');
	}

	/**
	 * 更新笔记本
	 * @param v
	 */
	const updateBookNote = useThrottleFn(async (v: NoteOftenEntity) => {
		await ApiNoteBookUpdate(v);
		getData();
		Message.success('操作成功');
	}, 4000);

	/**
	 * 更新笔记本名称
	 */
	async function updateBookNoteName(v: NoteOftenEntity) {
		if (v?.newValue) {
			await updateBookNote({ id: v.id, name: v.newValue });
		}
		if (v?.newValue != '') {
			v.edit = false;
		}
	}

	useBarAction('CenterSearch', () => {
		console.log('搜索');
	});

	const noteBookAddRef = useCompRef(NoteBookAdd);

	useBarAction('RightAdd', () => {
		noteBookAddRef.value?.open();
	});

	/**
	 * 更新笔记本封面
	 */
	const { handleOnChange, handleOpen } = useUploadFile();

	handleOnChange(async (files: FileList, param: any) => {
		const os = await ApiUpload(fileToFormData(files[0]));
		await updateBookNote({ ...param, coverUrl: os.filename });
	});

	const noteBookListRef = ref<HTMLElement | null>(null);

	/**
	 * 滚动加载
	 */
	useInfiniteScroll(
		noteBookListRef,
		useThrottleFn(async () => {
			if (pageNoTotal === query.value.pageNo) return;

			query.value.pageNo++;

			const data = await ApiNoteBookPage(query.value);
			if (data.list.length > 0) {
				noteBookList.value.push(...data.list);
			}
		}, 4000),
		{ distance: 10 },
	);

	/**
	 * 动态设置列表高度
	 */
	useResizeObserver(
		everydayRef,
		useDebounceFn((entries) => {
			const entry = entries[0];
			nextTick(() => {
				const height = entry.contentRect.height ? entry.contentRect.height + 40 : 0;

				if (noteBookListRef.value) {
					noteBookListRef.value.style.height = `calc(100% - ${height}px)`;
				}
			});
		}, 50),
	);
</script>

<template>
	<div
		ref="everydayRef"
		class="everyday bg-[#fafafa] p-[20px] rounded-[10px]"
	>
		<a-collapse
			:default-active-key="['1']"
			accordion
			:show-expand-icon="false"
			:bordered="false"
		>
			<a-collapse-item
				header="展开"
				key="1"
			>
				<a-grid
					:cols="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }"
					:colGap="12"
					:rowGap="16"
				>
					<a-grid-item
						class="item"
						v-for="v in noteOftenList"
						:key="v.id"
					>
						<a-input
							class="w-70%!"
							placeholder="请输入笔记名称"
							:error="v.newValue === ''"
							:ref="(el: any) => (v.ref = el)"
							:disabled="!v.edit"
							v-model="v.name"
							@input="(value: any) => (v.newValue = value)"
							@press-enter="() => updateBookNoteName(v)"
							@blur="() => updateBookNoteName(v)"
						/>
						<DropdownAction
							:items="[
								{
									label: '移出常用',
									type: 'text',
									icon: 'EachApp EachApp_quxiaochangyong',
									onClick: () => removeOften(v.id),
								},

								{
									label: '重命名',
									type: 'text',
									icon: 'EachApp EachApp_zhongmingming',
									onClick() {
										v.edit = true;
										$nextTick(() => v.ref?.focus());
									},
								},
								{
									label: '删除',
									type: 'danger',
									icon: 'EachApp EachApp_shanchu',

									onClick: () => {
										useMessageConfirm('error', {
											content: `确认要删除 [${v.name}] 笔记本吗？`,
											onOk: () => deleteNote(v),
										});
									},
								},
							]"
						/>
					</a-grid-item>
				</a-grid>
			</a-collapse-item>
		</a-collapse>
	</div>

	<div
		ref="noteBookListRef"
		class="list"
		v-if="noteBookList.length"
	>
		<a-grid
			:cols="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }"
			:colGap="12"
			:rowGap="16"
		>
			<a-grid-item
				v-for="v in noteBookList"
				:key="v.id"
				class="list-item"
			>
				<div
					class="cover"
					@click="router.push({ path: `${router.currentRoute.value.path}/detail/${v.id}` })"
				>
					<a-image
						:preview="false"
						width="100%"
						height="100%"
						:src="FILE_PREVIEW + v.coverUrl"
					/>
					<i
						@click.stop="() => handleOpen(v)"
						class="EachApp EachApp_a-bianji1"
					></i>
				</div>

				<div class="info w-full">
					<div class="w-full flex justify-between items-center pr-10px">
						<div
							class="w-10px h-25px"
							v-show="!v.edit"
						>
							📒
						</div>
						<a-input
							class="w-75%! mr-auto mb-5px"
							placeholder="请输入笔记名称"
							:error="v.newValue === ''"
							:ref="(el: any) => (v.ref = el)"
							:disabled="!v.edit"
							v-model="v.name"
							@input="(value: any) => (v.newValue = value)"
							@press-enter="() => updateBookNoteName(v)"
							@blur="() => updateBookNoteName(v)"
						/>

						<DropdownAction
							:items="[
								{
									label: v.isOften ? '移出常用' : '添加常用',
									type: 'text',
									icon: v.isOften ? 'EachApp EachApp_quxiaochangyong' : 'EachApp EachApp_changyongziliao',
									onClick: () => (v.isOften ? removeOften(v.id) : addOften(v.id)),
								},

								{
									label: '重命名',
									type: 'text',
									icon: 'EachApp EachApp_zhongmingming',
									onClick() {
										v.edit = true;
										$nextTick(() => v.ref?.focus());
									},
								},
								{
									label: '删除',
									type: 'danger',
									icon: 'EachApp EachApp_shanchu',
									onClick: () => {
										useMessageConfirm('error', {
											content: `确认要删除 [${v.name}] 笔记本吗？`,
											onOk: () => deleteNote(v),
										});
									},
								},
							]"
						/>
					</div>

					<span class="remark">{{ v.remark }}</span>
				</div>
			</a-grid-item>
		</a-grid>
	</div>

	<a-empty
		class="mt-10%"
		v-else
	/>

	<NoteBookAdd
		@ok="getNoteBookList"
		ref="noteBookAddRef"
	/>
</template>

<style scoped lang="scss">
	.everyday {
		:deep(.arco-collapse) {
			.arco-collapse-item {
				position: relative;

				&:before {
					position: absolute;
					content: '常用';
					font-weight: 700;
					color: #585a5a;
					height: 20px;
					line-height: 20px;
					font-size: 13px;
				}
			}

			.arco-collapse-item-header {
				width: 50px;
				line-height: 20px;
				height: 20px;
				padding: 0;
				color: #0e42d2;
				text-align: center;
				margin-left: auto;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 13px;
				background: transparent;
				border: none;
				user-select: none;
			}

			.arco-collapse-item-content {
				padding: 0;
				background: transparent;
			}

			.arco-collapse-item-content-box {
				.item {
					border-radius: 6px;
					padding: 19px 28px 16px 20px;
					display: flex;
					align-items: center;
					justify-content: space-between;
					height: 64px;
					position: relative;
					background: white;
					border: 1px solid #f4f5f5;
					cursor: grab;

					&:hover {
						i {
							opacity: 1;
						}
					}

					> i {
						padding: 3px 6px;
						opacity: 0;
						border-radius: 4px;
						transition:
							opacity 0.3s,
							background 0.3s;

						cursor: pointer;

						& {
							background: #eee;
						}
					}
				}
			}
		}
	}

	:deep(.arco-input) {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-size: 14px !important;
	}

	:deep(.arco-input-wrapper.arco-input-disabled) {
		background: transparent;
		cursor: grab;

		.arco-input[disabled] {
			-webkit-text-fill-color: rgb(51, 51, 51);
		}
	}

	.list {
		overflow-y: scroll;
		padding-right: 5px;
		height: 100%;
		padding-top: 10px;

		&-item {
			border: 1px solid #e7e9e8;
			border-radius: 10px;
			overflow: hidden;
			cursor: pointer;

			&:hover {
				box-shadow: 0 3px 10px 4px #eee;
				transition: all 0.3s;

				i {
					opacity: 1 !important;
				}
			}

			.cover {
				height: 290px;
				//background-image: url('./test.jpg');
				background-position: center;
				background-repeat: no-repeat;
				background-size: cover;
				position: relative;
				border-bottom: 1px solid #e7e9e8;

				i {
					position: absolute;
					right: 10px;
					top: 10px;
					background: #888;
					z-index: 9;
					border-radius: 4px;
					width: 22px;
					height: 22px;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;
					opacity: 0;
					transition: opacity 0.3s;
				}
			}

			.info {
				padding: 0 0 0 15px;
				height: 85px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				max-width: 100%;
				width: 100%;

				i {
					padding: 3px 6px;
					opacity: 0;
					border-radius: 4px;
					transition:
						opacity 0.3s,
						background 0.3s;
					margin-right: 10px;
					cursor: pointer;

					&:hover {
						background-color: #eee;
					}
				}

				.remark {
					color: #999;
					font-size: 11px;
					overflow: hidden;
					width: 95%;
					white-space: nowrap;
					text-overflow: ellipsis;
					font-weight: 400;
					height: 27px;
					line-height: 13px;
				}
			}
		}
	}
</style>
